package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.EngineMsg;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.NoticeService;
import com.cci.kangdao.service.WorkOrderCommTService;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.SmsUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//用户App评价接口实现类
@Service("WorkOrderCommT")
public class WorkOrderCommTServiceImpl implements WorkOrderCommTService{

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private WorkOrderCommTDao workOrderCommTDao;

	@Autowired
	private LoginDao loginDao;

	@Autowired
	private WorkOrderTDao workOrderTDao;


	@Resource
	private CRMPlatformServiceDao platformServiceDao;

	@Resource
	private WorkOrderRepairDao workOrderRepairDao;

	@Autowired
	private CompanyTDao companyTDao;

	@Autowired
	private RedisClientUtils redisClientUtils;

	@Resource
	private WorkOrderTServiceImpl workOrderTServiceImpl;
	@Resource
	private NoticeService noticeService;
	@Resource
	private ServiceStationDao serviceStationDao;
	@Resource
	private EngineMsgDao engineMsgDao;

	//用户App评价接口
	@Transactional
	@Override
	public ModelAndView userAPPAppraise(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			//保存用户app评价信息到表中
			int saveWorkOrderCommTFlag = saveWorkOrderCommT(map);   //返回0为成功，1为失败
			//保存工单信息
			int saveWorkOrderByUserAPPAppraiseResult = saveWorkOrderByUserAPPAppraise(map);
			if(saveWorkOrderByUserAPPAppraiseResult == 0){
				obj.put("status", SMSEnum.type21.getIndex());
				obj.put("msg", SMSEnum.type21.getName());
				obj.put("data", "");
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			//保存工单操作记录表信息
			saveOperation(map);
			
			
			//同步CRM系统工单状态信息
			syncOrderStatusToCrm(map);
			
			
			//APP系统同步用户评价信息到CRM系统
			syncUserAppraise(map);
			if(saveWorkOrderCommTFlag == 0) {
				obj.put("status", 0);
				obj.put("msg", "用户App评价成功!");
				obj.put("data", "");
			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

	//保存用户app评价信息到表中
	public int saveWorkOrderCommT(Map<String, Object> map) {
		//workOrderId,backNormal,satisfaction,unSatisfiedReason
		//unSatisfiedExplain,isCharged,willShare,shareReason,shareExplain
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
        //String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
        UserT loginUserT = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		JSONObject obj = new JSONObject();
		//创建保存用户app评论map
		Map<String, Object> workOrderCommTMap = new HashMap<String, Object>();
		if(!map.containsKey("companyId")){
			try {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "服务渠道id不能为空!");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			ParameterTool.writeResponse(response, obj.toString());
			return 1;
		}
		long companyId = Long.parseLong(map.get("companyId").toString());  //服务渠道id
		String workOrderId = (String)map.get("workOrderId");
		if("".equals(workOrderId) || workOrderId == null) {
			try {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			ParameterTool.writeResponse(response, obj.toString());
			return 1;
		}

		//xcec工单类型（0:发动机维修   1:售时服务）
		Map<String,Object> workOrderMap = workOrderTDao.getOrderById(Long.parseLong(workOrderId));
		int orderType = MapUtils.getIntValue(workOrderMap,"OrderType",0);
		if(companyId == 4 && orderType == 1){  //xcec售时工单用户评价界面和其他都不一样，这里单写一个
			//IsCheckEngine int default 0  --发动机是否检查   默认否

			workOrderCommTMap.put("orderId", workOrderId);
			String isCheckEngine = MapUtils.getString(map,"isCheckEngine","");
			if(StringUtils.isEmpty(isCheckEngine)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "发动机是否检查不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			workOrderCommTMap.put("isCheckEngine", Integer.parseInt(isCheckEngine));
			String satisfaction = MapUtils.getString(map,"satisfaction","");
			if(StringUtils.isEmpty(satisfaction)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "服务是否满意不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			String unSatisfiedReason = MapUtils.getString(map,"unSatisfiedReason","");
			if(Integer.parseInt(satisfaction) == 0) { //0为不满意，1为满意(不满意时，不满意原因必填)
				if(StringUtils.isEmpty(unSatisfiedReason)) {
					try {
						obj.put("data", "");
						obj.put("status", 1);
						obj.put("msg", "不满意原因不能为空!");
					} catch (JSONException e) {
						e.printStackTrace();
					}
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
			}
			String unSatisfiedExplain = MapUtils.getString(map,"unSatisfiedExplain","");  //不满意具体说明

			workOrderCommTMap.put("satisfaction", Integer.parseInt(satisfaction));  //是否满意(0：否，1：是)
			if(Integer.parseInt(satisfaction) == 0) {
				workOrderCommTMap.put("unSatisfiedReason", unSatisfiedReason);  //不满意原因
				if(StringUtils.isNotEmpty(unSatisfiedExplain)) {
					workOrderCommTMap.put("unSatisfiedExplain", unSatisfiedExplain);  //不满意具体说明
				}
			}
			//IsTraining int default 0   --驾驶习惯、保养规范是否培训   默认否
			String isTraining = MapUtils.getString(map,"isTraining","");
			if(StringUtils.isEmpty(isTraining)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "驾驶习惯、保养规范是否培训不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			workOrderCommTMap.put("isTraining", Integer.parseInt(isTraining));
			workOrderCommTDao.insertWorkOrderCommT(workOrderCommTMap);
		}else{
			String backNormal = MapUtils.getString (map,"backNormal");
			if(companyId != 1 && StringUtils.isEmpty(backNormal)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "是否修复不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			if(companyId == 3 || companyId == 4){  //当服务渠道id是DCEC和XCEC时    服务是否满意，不满意原因，不满意具体描述不能为空   DBU没有服务是否满意相关信息
				String satisfaction = (String)map.get("satisfaction");
				if("".equals(satisfaction) || satisfaction == null) {
					try {
						obj.put("data", "");
						obj.put("status", 1);
						obj.put("msg", "服务是否满意不能为空!");
					} catch (JSONException e) {
						e.printStackTrace();
					}
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
				String unSatisfiedReason = (String)map.get("unSatisfiedReason");
				if(Integer.parseInt(satisfaction) == 0) { //0为不满意，1为满意(不满意时，不满意原因必填)
					if("".equals(unSatisfiedReason) || unSatisfiedReason == null) {
						try {
							obj.put("data", "");
							obj.put("status", 1);
							obj.put("msg", "不满意原因不能为空!");
						} catch (JSONException e) {
							e.printStackTrace();
						}
						ParameterTool.writeResponse(response, obj.toString());
						return 1;
					}
				}
				String unSatisfiedExplain = (String)map.get("unSatisfiedExplain");  //不满意具体说明

				workOrderCommTMap.put("satisfaction", Integer.parseInt(satisfaction));  //是否满意(0：否，1：是)
				if(Integer.parseInt(satisfaction) == 0) {
					workOrderCommTMap.put("unSatisfiedReason", unSatisfiedReason);  //不满意原因
					if(!"".equals(unSatisfiedExplain)  && unSatisfiedExplain != null) {
						workOrderCommTMap.put("unSatisfiedExplain", unSatisfiedExplain);  //不满意具体说明
					}
				}
			}
			String isCharged = MapUtils.getString (map,"isCharged");
			if(companyId != 1 && StringUtils.isEmpty(isCharged)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "保内车是否收费不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			String willShare = MapUtils.getString (map,"willShare");
			if(companyId != 1 && StringUtils.isEmpty(willShare)) {
				try {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "是否愿意将e路康明斯推荐给他人分数不能为空!");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ParameterTool.writeResponse(response, obj.toString());
				return 1;
			}
			String shareReason = MapUtils.getString (map,"shareReason");
			if(companyId != 1 && Integer.parseInt(willShare) <= 6) {  //当是否愿意将东风康明斯推荐给他人分数小于6分的时候，不愿意原因必填
				if("".equals(shareReason) || shareReason == null) {
					try {
						obj.put("data", "");
						obj.put("status", 1);
						obj.put("msg", "不愿意将东风康明斯推荐给他人原因不能为空!");
					} catch (JSONException e) {
						e.printStackTrace();
					}
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
			}
			String shareExplain = MapUtils.getString (map,"shareExplain");  //不愿意具体说明
			workOrderCommTMap.put("orderId", Long.parseLong(workOrderId));  //工单id
            if(companyId != 1){
                workOrderCommTMap.put("backNormal", Integer.parseInt(backNormal));//是否恢复正常(0：否，1：是)
                workOrderCommTMap.put("isCharged", Integer.parseInt(isCharged)); //保内车是否收费(0：否，1：是)
                workOrderCommTMap.put("willShare", Integer.parseInt(willShare));//是否愿意分享分数
                if(companyId != 1 && Integer.parseInt(willShare) <= 6) {
                    workOrderCommTMap.put("shareReason", shareReason);
                    if(!"".equals(shareExplain) && shareExplain != null) {
                        workOrderCommTMap.put("shareExplain", shareExplain);
                    }
                }
            }
			workOrderCommTMap.put("flag", 0);
			workOrderCommTMap.put("creator", loginUserT.getId());
			workOrderCommTMap.put("createTime", currentTime);
			String repairReasonDescription = "";  //维修原因描述
			if(map.containsKey("repairReasonDescription")){
				repairReasonDescription = map.get("repairReasonDescription").toString();
			}
			workOrderCommTMap.put("repairReasonDescription", repairReasonDescription);
			if(companyId == 1){

				if(checkEmpty(map,"cumminsProductServiceSumRecommendValue","康明斯产品和服务总体推荐值不能为空!",obj) != 0){
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
				int cumminsProductServiceSumRecommendValue = MapUtils.getIntValue(map,"cumminsProductServiceSumRecommendValue");
				//2.5.0需求     dbu用户分数在8分及8分以下需要填建议，9/10分选填建议
				if(cumminsProductServiceSumRecommendValue <= 8){
					if(checkEmpty(map,"cumminsProductServiceSumRecommendValueSuggest","康明斯产品和服务总体推荐值建议不能为空!",obj) != 0){
						ParameterTool.writeResponse(response, obj.toString());
						return 1;
					}
				}

				if(checkEmpty(map,"cumminsServiceSatisfactionValue","康明斯服务满意值不能为空!",obj) != 0){
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
				int cumminsServiceSatisfactionValue = MapUtils.getIntValue(map,"cumminsServiceSatisfactionValue");
				if(cumminsServiceSatisfactionValue <=8 ){
					if(checkEmpty(map,"cumminsServiceSatisfactionValueSuggest","康明斯服务满意值建议不能为空!",obj) != 0){
						ParameterTool.writeResponse(response, obj.toString());
						return 1;
					}
				}
                //2.10.0运维版本去掉下面两项
				/*if(checkEmpty(map,"cumminsProductSatisfactionValue","康明斯产品满意值不能为空!",obj) != 0){
					ParameterTool.writeResponse(response, obj.toString());
					return 1;
				}
				int cumminsProductSatisfactionValue = MapUtils.getIntValue(map,"cumminsProductSatisfactionValue");
				if(cumminsProductSatisfactionValue <= 8){
					if(checkEmpty(map,"cumminsProductSatisfactionValueSuggest","康明斯产品满意值建议不能为空!",obj) != 0){
						ParameterTool.writeResponse(response, obj.toString());
						return 1;
					}
				}*/
				workOrderCommTMap.put("cumminsProductServiceSumRecommendValue",cumminsProductServiceSumRecommendValue);
				workOrderCommTMap.put("cumminsProductServiceSumRecommendValueSuggest",MapUtils.getString(map,"cumminsProductServiceSumRecommendValueSuggest",""));
				workOrderCommTMap.put("cumminsServiceSatisfactionValue",MapUtils.getIntValue(map,"cumminsServiceSatisfactionValue"));
				workOrderCommTMap.put("cumminsServiceSatisfactionValueSuggest",MapUtils.getString(map,"cumminsServiceSatisfactionValueSuggest",""));
				/*workOrderCommTMap.put("cumminsProductSatisfactionValue",MapUtils.getIntValue(map,"cumminsProductSatisfactionValue"));
				workOrderCommTMap.put("cumminsProductSatisfactionValueSuggest",MapUtils.getString(map,"cumminsProductSatisfactionValueSuggest",""));*/
			}
			if(map.containsKey("memberServiceSatisfactionValue")){
				workOrderCommTMap.put("memberServiceSatisfactionValue",MapUtils.getIntValue(map,"memberServiceSatisfactionValue"));
				int memberServiceSatisfactionValue = MapUtils.getIntValue(map,"memberServiceSatisfactionValue");
				if(memberServiceSatisfactionValue <= 8){
					if(checkEmpty(map,"memberServiceSatisfactionValueSuggest","大运会员预约服务满意值建议不能为空!",obj) != 0){
						ParameterTool.writeResponse(response, obj.toString());
						return 1;
					}
				}
				workOrderCommTMap.put("memberServiceSatisfactionValueSuggest",MapUtils.getString(map,"memberServiceSatisfactionValueSuggest",""));
			}
			workOrderCommTDao.insertWorkOrderCommT(workOrderCommTMap);
		}
		return 0;
	}

	//校验map中是否有某个字段
	public int checkEmpty(Map<String,Object> map,String key,String msg,JSONObject obj){
		int status = 0;
		if(!map.containsKey(key)){
			status = 1;
			try {
				obj.put("data", "");
				obj.put("status", status);
				obj.put("msg", msg);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return  status;
	}

	//APP系统同步用户评价信息到CRM系统
	public void syncUserAppraise(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		Map<String, Object> parameters = new HashMap<String, Object>();
		long orderId = MapUtils.getLongValue(map,"workOrderId");
		Map<String,Object> workOrderMap = workOrderTDao.getOrderById(orderId);
		map.put("ID", Long.parseLong((String) map.get("workOrderId")));
		WorkOrderT workOrderT = workOrderTDao.getWorkOrderTById(map);
		long companyId = workOrderT.getOrderChannel();  //服务渠道
		if(MapUtils.getLongValue(workOrderMap,"OrderChannel") == 4 && MapUtils.getIntValue(workOrderMap,"OrderType",0) == 1){
			//xcec售时工单
			//根据工单id获取用户评价信息
			if (map.containsKey("satisfaction")) {
				int satisfaction = Integer.parseInt((String) map.get("satisfaction"));
				parameters.put("isServiceSatisfied", satisfaction);
				if (satisfaction == 0) {
					parameters.put("serviceContent", (String) map.get("unSatisfiedReason"));
				}
				String unSatisfiedExplain = (String) map.get("unSatisfiedExplain");  //不满意具体说明
				if (StringUtils.isNotBlank(unSatisfiedExplain)) {
					parameters.put("serviceDescription", unSatisfiedExplain);
				}
			}
			parameters.put("isCheckEngine", MapUtils.getIntValue(map,"isCheckEngine"));
			parameters.put("isTraining", MapUtils.getIntValue(map,"isTraining"));
		}else {
			if (StringUtils.isNotBlank(workOrderT.getOrderNoCrm())) {
				parameters.put("crmNo", workOrderT.getOrderNoCrm());
			}
			parameters.put("orderNo", workOrderT.getOrderNo());
			if(companyId != 1){
				parameters.put("hasRepair", Integer.parseInt((String) map.get("backNormal")));
				parameters.put("isCharge", Integer.parseInt((String) map.get("isCharged")));
			}
			if (map.containsKey("satisfaction")) {
				int satisfaction = Integer.parseInt((String) map.get("satisfaction"));
				parameters.put("isServiceSatisfied", satisfaction);
				if (satisfaction == 0) {
					parameters.put("serviceContent", (String) map.get("unSatisfiedReason"));
				}
				String unSatisfiedExplain = (String) map.get("unSatisfiedExplain");  //不满意具体说明
				if (StringUtils.isNotBlank(unSatisfiedExplain)) {
					parameters.put("serviceDescription", unSatisfiedExplain);
				}
			}


			if (workOrderT.getOrderChannel() == 1) {  //DBU
				//parameters.put("userScores", (String) map.get("willShare"));
				//String shareExplain = MapUtils.getString(map, "shareExplain", "");
				//String shareReason = MapUtils.getString(map, "shareReason", "");
				//String poorRateReason = String.format("%s;%s", shareReason, shareExplain);
				//parameters.put("poorRateReason", poorRateReason);
				parameters.put("cumminsProductServiceSumRecommendValue", MapUtils.getIntValue(map, "cumminsProductServiceSumRecommendValue"));
				parameters.put("cumminsProductServiceSumRecommendValueSuggest", MapUtils.getString(map, "cumminsProductServiceSumRecommendValueSuggest",""));
				parameters.put("cumminsServiceSatisfactionValue", MapUtils.getIntValue(map, "cumminsServiceSatisfactionValue"));
				parameters.put("cumminsServiceSatisfactionValueSuggest", MapUtils.getString(map, "cumminsServiceSatisfactionValueSuggest",""));
				parameters.put("cumminsProductSatisfactionValue", MapUtils.getIntValue(map, "cumminsProductSatisfactionValue"));
				parameters.put("cumminsProductSatisfactionValueSuggest", MapUtils.getString(map, "cumminsProductSatisfactionValueSuggest",""));
			} else {
				int willShare = Integer.parseInt((String) map.get("willShare"));
				parameters.put("recommendScores", (String) map.get("willShare"));
				if (willShare <= 6) {
					parameters.put("recommendDescription", (String) map.get("shareReason"));
				}
				String shareExplain = (String) map.get("shareExplain");  //不愿意具体说明
				if (StringUtils.isNotBlank(shareExplain)) {
					parameters.put("recommendReason", shareExplain);
				}
			}
			String repairReasonDescription = "";  //维修原因描述
			if (map.containsKey("repairReasonDescription")) {
				repairReasonDescription = map.get("repairReasonDescription").toString();
			}
			parameters.put("repairReasonDescription", repairReasonDescription);
		}
		String companyNo = companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo();
		try {
			CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().syncUserAppraisalInfoToCrm(companyNo,platformServiceDao,redisClientUtils,parameters);
			if(cRMResponeEntity.getStatus() != 0) {
				log.error("APP系统同步用户评价信息到CRM系统失败!状态:" + cRMResponeEntity.getStatus() + ",错误信息:" + cRMResponeEntity.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("APP系统同步用户评价信息到CRM系统失败!错误信息:" + e.getMessage(),e);
		}
	}

	//用户app评价完修改工单状态
	public int saveWorkOrderByUserAPPAppraise(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		//String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		//UserT loginUserT = loginDao.getUserByid(userADId);
		UserT loginUserT = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		map.put("ID", Long.parseLong((String)map.get("workOrderId")));
		map.put("OrderStatus", 14);  //工单状态为服务完成
		map.put("Updator", loginUserT.getId());
		map.put("UpdateTime", currentTime);
		String oldUpdateTime = MapUtils.getString(map,"oldUpdateTime","");
		if(StringUtils.isNotEmpty(oldUpdateTime)){
			map.put("oldUpdateTime",oldUpdateTime);
		}
		//更新工单信息
		int saveWorkOrderByUserAPPAppraiseResult = workOrderTDao.saveWorkOrderByUserAPPAppraise(map);
		return saveWorkOrderByUserAPPAppraiseResult;
	}

	//用户app评价完添加工单操作记录表数据
	public void saveOperation(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		/*String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		UserT loginUserT = loginDao.getUserByid(userADId);*/
		UserT loginUserT = UserThreadLocal.get();
		Long userid = loginUserT.getId();
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		Map<String, Object> workOrderFlowTMap = new HashMap<String, Object>();  //新建工单操作记录对象
		workOrderFlowTMap.put("OrderId", Long.parseLong((String)map.get("workOrderId")));
		workOrderFlowTMap.put("ProcessorId", userid);
		workOrderFlowTMap.put("OrderStatus", 14);  //工单状态为服务完成
		workOrderFlowTMap.put("ProcessComment", "服务已完成");
		workOrderFlowTMap.put("ProLocLon", /*Float.parseFloat((String)map.get("locLon"))*/MapUtils.getFloatValue(map,"locLon",  0));
		workOrderFlowTMap.put("ProLocLat", /*Float.parseFloat((String)map.get("locLat"))*/MapUtils.getFloatValue(map,"locLat",  0));
		workOrderFlowTMap.put("ProLocation",map.get("location"));
		workOrderFlowTMap.put("IMEI", map.get("IMEI"));  //手机串号
		workOrderFlowTMap.put("Flag", 0);
		workOrderFlowTMap.put("Creator",userid);
		workOrderFlowTMap.put("CreateTime", currentTime);
		workOrderRepairDao.saveOperation(workOrderFlowTMap);  //插入并保存工单操作记录数据
	}

	//同步工单状态信息给CRM
	public void syncOrderStatusToCrm(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		//String userADId = AESTool.decryptString(request.getHeader("userid"));//解密userid
		//UserT loginUserT = loginDao.getUserByid(userADId);
		UserT loginUserT = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		map.put("ID", Long.parseLong((String)map.get("workOrderId")));
		WorkOrderT workOrderT = workOrderTDao.getWorkOrderTById(map);
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("orderNo",workOrderT.getOrderNo());
		parameters.put("billStatus",14);
		parameters.put("actionTime",currentTime);
		parameters.put("directorName",loginUserT.getContact());
		parameters.put("directorPhone",loginUserT.getPhone());
		if(CollectionUtils.isNotEmpty(loginDao.getUserByPhone(workOrderT.getCustomerPhone()))){
			parameters.put("appAppraise",1);
		}else{
			parameters.put("appAppraise",0);
		}
		parameters.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
		parameters.put("positionLat",MapUtils.getFloatValue(map,"locLat",0));
		parameters.put("positionLon",MapUtils.getFloatValue(map,"locLon",0));
		parameters.put("location",MapUtils.getString(map,"location",""));
		String companyNo = companyTDao.getCompanyInfoByCompanyID(workOrderT.getOrderChannel()).getCompanyNo();
		
		
		try {
			CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyNo,platformServiceDao,redisClientUtils,parameters,null);
			if(cRMResponeEntity.getStatus() != 0) {
				log.error("同步工单状态至CRM失败!状态:" + cRMResponeEntity.getStatus() + ",错误信息:" + cRMResponeEntity.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
		}
	}



	//根据工单id获取用户评价信息
	@Transactional
	@Override
	public ModelAndView userAppraiseMsg(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		try{
			JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
			if(!map.containsKey("orderId")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			long orderId = MapUtils.getLongValue(map,"orderId");
			Map<String,Object> workOrderMap = workOrderTDao.getOrderById(orderId);
			if(MapUtils.getLongValue(workOrderMap,"OrderChannel") == 4 && MapUtils.getIntValue(workOrderMap,"OrderType",0) == 1){
				//xcec售时工单
				//根据工单id获取用户评价信息
				Map<String,Object> userAppraiseMsg = workOrderCommTDao.getXCECSSUserAppraiseMsgByOrderId(orderId);
				obj.put("data", new JSONObject().put("userAppraiseMsg",userAppraiseMsg));
			}else{
				//根据工单id获取用户评价信息
				Map<String,Object> userAppraiseMsg = workOrderCommTDao.getUserAppraiseMsgByOrderId(orderId);
				obj.put("data", new JSONObject().put("userAppraiseMsg",userAppraiseMsg));
			}
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}




	//ccec用户评价接口
	@Transactional
	@Override
	public ModelAndView userAPPAppraiseForCCEC(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		HttpServletRequest request = (HttpServletRequest)map.get("request");
		UserT userT = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();  //获取当前时间
		JSONObject obj = new JSONObject();   //保存返给手机端的数据容器
		Map<String,Object> insertWorkOrderCommMap = new HashMap<>();
		try{
			if(!map.containsKey("orderId")){
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "服务工单id不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			long orderId = MapUtils.getLongValue(map,"orderId");
			Map<String,Object> workOrderMap = workOrderTDao.getOrderById(orderId);
			int currentOrderStatus = MapUtils.getIntValue(workOrderMap,"OrderStatus");
			if(currentOrderStatus == 13){    // 13	 待用户评价         28  待用户评价--400远程解决
				if(!map.containsKey("serviceIsFinish")){
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "服务是否完成不能为空!");
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
				insertWorkOrderCommMap.put("serviceIsFinish",MapUtils.getIntValue(map,"serviceIsFinish",1));
				if(!map.containsKey("willShareServiceStationGrades")) {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "是否愿意推荐这家服务站商给他人分数不能为空!");
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
				int willShareServiceStationGrades = MapUtils.getIntValue(map,"willShareServiceStationGrades");
				insertWorkOrderCommMap.put("willShareServiceStationGrades",willShareServiceStationGrades);
				if(willShareServiceStationGrades <= 8) {  //当是否愿意推荐这家服务站商给他人分数小于8分的时候，不愿意推荐原因必填
					if(!map.containsKey("notRecommendServiceStationReason")) {
						obj.put("data", "");
						obj.put("status", 1);
						obj.put("msg", "不愿意推荐原因不能为空!");
						ParameterTool.writeResponse(response, obj.toString());
						return null;
					}
					insertWorkOrderCommMap.put("notRecommendServiceStationReason",MapUtils.getString(map,"notRecommendServiceStationReason",""));
					insertWorkOrderCommMap.put("notRecommendServiceStationExplain",MapUtils.getString(map,"notRecommendServiceStationExplain",""));
				}
			}
			//分享重庆康明斯分数 ，不分享原因   不分享描述  属于待用户评价以及待用户评价-400远程解决共用的
			if(!map.containsKey("willShareCompanyGrades")) {
				obj.put("data", "");
				obj.put("status", 1);
				obj.put("msg", "是否愿意将e路康明斯推荐给他人分数不能为空!");
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			int willShareCompanyGrades = MapUtils.getIntValue(map,"willShareCompanyGrades");
			insertWorkOrderCommMap.put("willShare",MapUtils.getIntValue(map,"willShareCompanyGrades"));
			if(willShareCompanyGrades <= 8) {  //当是否愿意将e路康明斯推荐给他人分数小于8分的时候，不愿意推荐原因必填
				if(!map.containsKey("notRecommendCompanyReason")) {
					obj.put("data", "");
					obj.put("status", 1);
					obj.put("msg", "不愿意推荐原因不能为空!");
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
				insertWorkOrderCommMap.put("shareReason",MapUtils.getString(map,"notRecommendCompanyReason",""));
				insertWorkOrderCommMap.put("shareExplain",MapUtils.getString(map,"notRecommendCompanyExplain",""));
			}
			insertWorkOrderCommMap.put("orderId",orderId);
			insertWorkOrderCommMap.put("flag",0);
			insertWorkOrderCommMap.put("creator",userT.getId());
			insertWorkOrderCommMap.put("createTime",currentTime);
			int insertWorkOrderCommTResult = workOrderCommTDao.insertWorkOrderCommT(insertWorkOrderCommMap);  //插入用户评价表
			//待用户评价-400远程解决时  28  提交用户评价后   工单状态改为14 服务完成
			int orderStatus = 14;           //14	服务完成
			//待用户评价中  13   服务是否完成    选择是   工单状态为14    选择否   工单状态为32
			int serviceIsFinish = MapUtils.getIntValue(map,"serviceIsFinish",1);
			if(currentOrderStatus == 13 && serviceIsFinish == 0){   //0：否     1：是
				orderStatus = 32;    //32	 待400回访
			}
			map.put("ID", orderId);
			map.put("OrderStatus", orderStatus);
			map.put("Updator", userT.getId());
			map.put("UpdateTime", currentTime);
			map.put("oldUpdateTime",MapUtils.getString(map,"oldUpdateTime",""));
			//更新工单信息
			int saveWorkOrderByUserAPPAppraiseResult = workOrderTDao.saveWorkOrderByUserAPPAppraise(map);  //修改工单状态
			if(saveWorkOrderByUserAPPAppraiseResult == 0){
				obj.put("status", SMSEnum.type21.getIndex());
				obj.put("msg", SMSEnum.type21.getName());
				obj.put("data", "");
				// 主动回滚事务
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				//返回客户
				ParameterTool.writeResponse(response, obj.toString());
				return null;
			}
			String  locLon = MapUtils.getString (map,"locLon");
			String  locLat = MapUtils.getString (map,"locLat");
			String  location = MapUtils.getString (map,"location");
			String  IMEI = MapUtils.getString (map,"IMEI");
			//工单状态为服务完成   没有负责人   没有消息推送
			//工单状态为待400回访    负责人是服务站的400    推给400消息
			if(orderStatus == 14){
				//插入工单操作记录表
				workOrderTServiceImpl.saveOperation(orderId,userT.getId(),orderStatus,"用户评价--服务完成",locLon,locLat,location,IMEI,0,userT.getId(),currentTime);
			}else{
				//插入工单操作记录表
				workOrderTServiceImpl.saveOperation(orderId,userT.getId(),orderStatus,"用户评价--待400回访",locLon,locLat,location,IMEI,0,userT.getId(),currentTime);
				map.put("ServiceStationId",MapUtils.getLong(workOrderMap,"ServiceStationId"));
				map.put("OrderChannel",MapUtils.getLong(workOrderMap,"OrderChannel"));
				List<Map<String,Object>> notifyRecordTMapList = new ArrayList<>();
				List<Map<String,Object>> AreaManagerMapList = workOrderRepairDao.getAreaManager(map);
				String msgbody = "";
				if(StringUtils.isNotEmpty(MapUtils.getString(workOrderMap,"CCSSOrderNo",""))){
					msgbody = "您有工单待回访，工单号"+MapUtils.getString(workOrderMap,"OrderNo")+"（FW号"+MapUtils.getString(workOrderMap,"CCSSOrderNo","")+"），请处理。";
				}else{
					msgbody = "您有工单待回访，工单号"+MapUtils.getString(workOrderMap,"OrderNo")+"，请处理。";
				}
				if(CollectionUtils.isNotEmpty(AreaManagerMapList)){
					for(Map<String,Object> AreaManagerMap : AreaManagerMapList){
						long  receiverId = MapUtils.getLongValue(AreaManagerMap,"ID");
						String receiverUserName = MapUtils.getString(AreaManagerMap,"UserName");
						String phone = MapUtils.getString(AreaManagerMap,"phone","");
						workOrderTServiceImpl.savePrincipal(orderId,orderStatus,1,receiverId,userT.getId(),currentTime);
						noticeService.push(2,1,orderId,receiverId,receiverUserName,"新工单提醒",msgbody,msgbody,userT.getId());
						SmsUtils.sendMessage(phone, msgbody);
						notifyRecordTMapList.add(workOrderTServiceImpl.saveMsgOperation(orderId,2,1,receiverId,msgbody,1,currentTime,"",userT.getId()));
					}
					if(CollectionUtils.isNotEmpty(notifyRecordTMapList)){
						workOrderRepairDao.saveMsgOperation(notifyRecordTMapList);
					}
				}
			}
			//调用2.2.3 APP系统同步工单状态信息到CRM系统
			Map<String, Object> parameters1 = new HashMap<>();
			parameters1.put("orderNo",MapUtils.getString(workOrderMap,"OrderNo"));
			parameters1.put("CRMNo",MapUtils.getString(workOrderMap,"OrderNoCrm"));
			parameters1.put("billStatus",orderStatus);
			parameters1.put("actionTime",currentTime);
			parameters1.put("directorName",userT.getContact());
			parameters1.put("directorPhone",userT.getPhone());
			parameters1.put("positionLat",locLat);
			parameters1.put("positionLon",locLon);
			parameters1.put("phoneIMEI",IMEI);
			parameters1.put("location",location);
			parameters1.put("CCSSComplainerOrderNo",MapUtils.getString(workOrderMap,"OrderNoCrm"));
			parameters1.put("CCSSOrderNo",MapUtils.getString(workOrderMap,"CCSSOrderNo"));
			parameters1.put("customerName",MapUtils.getString(workOrderMap,"CustomerName"));
			parameters1.put("customerPhone",MapUtils.getString(workOrderMap,"CustomerPhone"));
			parameters1.put("customerCompany",MapUtils.getString(workOrderMap,"CustomerCompanyName"));
			parameters1.put("faultDesc",MapUtils.getString(workOrderMap,"CustomerComplaint"));
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLong(workOrderMap,"ServiceStationId"),MapUtils.getLong(workOrderMap,"OrderChannel"));
			if(MapUtils.isNotEmpty(sSRepair)){
				parameters1.put("stationNo",sSRepair.get("BusinessNo"));
				parameters1.put("stationName",sSRepair.get("StationName"));
			}else{
				parameters1.put("stationNo","");
				parameters1.put("stationName","");
			}
			parameters1.put("drOrderNNo","");
			parameters1.put("drDiagnoseReport","");
			parameters1.put("doneSolutionList",new ArrayList<>());
			parameters1.put("faultInfo","");
			parameters1.put("doneSolutionNoStr","");
			EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(MapUtils.getString(workOrderMap,"ESN",""));
			if(null != engineMsg){
				parameters1.put("SMN",engineMsg.getSMN());
			}else{
				parameters1.put("SMN","");
			}
			try {
				CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(MapUtils.getLong(workOrderMap,"OrderChannel")).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
				if(crmResponeEntity.getStatus() != 0) {
					log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
			}

			//调用2.2.15 APP系统同步工单评价信息到CRM系统
			Map<String, Object> parameters2 = new HashMap<>();
			parameters2.put("orderNo",MapUtils.getString(workOrderMap,"OrderNo"));
			parameters2.put("CCSSComplainerOrderNo",MapUtils.getString(workOrderMap,"OrderNoCrm"));
			parameters2.put("CCSSOrderNo",MapUtils.getString(workOrderMap,"CCSSOrderNo"));
			parameters2.put("isServiceCompletion",MapUtils.getIntValue(map,"serviceIsFinish",1));
			parameters2.put("recommendCCECScores",MapUtils.getIntValue(map,"willShareCompanyGrades",10));
			parameters2.put("recommendSSScores",MapUtils.getIntValue(map,"willShareServiceStationGrades",10));
			parameters2.put("recommendCCECDes",MapUtils.getString(map,"notRecommendCompanyReason",""));
			parameters2.put("recommendSSDes",MapUtils.getString(map,"notRecommendServiceStationReason",""));
			parameters2.put("recommendCCECThought",MapUtils.getString(map,"notRecommendCompanyExplain",""));
			parameters2.put("recommendSSThought",MapUtils.getString(map,"notRecommendServiceStationExplain",""));
			parameters2.put("appraiseTime",currentTime);
			if(currentOrderStatus == 13){
				parameters2.put("appraiseType",0);
			}else{
				parameters2.put("appraiseType",1);
			}
			try {
				CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().syncUserAppraisalInfoToCrm(companyTDao.getCompanyInfoByCompanyID(MapUtils.getLong(workOrderMap,"OrderChannel")).getCompanyNo(),platformServiceDao,redisClientUtils,parameters2);
				if(cRMResponeEntity.getStatus() != 0) {
					log.error("APP系统同步用户评价信息到CRM系统失败!状态:" + cRMResponeEntity.getStatus() + ",错误信息:" + cRMResponeEntity.getMessage());
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("APP系统同步用户评价信息到CRM系统失败!错误信息:" + e.getMessage(),e);
			}
			obj.put("status", 0);
			obj.put("msg", "success");
			obj.put("data", "");
			ParameterTool.writeResponse(response, obj.toString());
		} catch(Exception e) {
			ParameterTool.writeErrorResponse(response);
			//主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.error(e.getMessage(),e);
		}
		return null;
	}

}
